package com.machinecontroller.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.util.Log;

import java.util.List;

/**
 * 线程管理工具
 * Created by zhangxuehui on 2017/12/16.
 */
public class ServiceUitl {
    /**
     * 服务是在工作
     *
     * @param context
     * @param serviceName
     * @return
     */
    public static boolean isServiceWork(Context context, String serviceName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> list = am.getRunningServices(1000);
        if (list.size() <= 0) {
            return false;
        }
        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).service.getClassName();
            if (name.equals(serviceName)) {
                return true;
            }

        }
        return false;
    }

    /**
     * 进程是否运行
     *
     * @param context
     * @param processName
     * @return
     */
    public static boolean isProcessRunning(Context context, String processName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> list = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : list) {
            Log.i(context.getPackageName(), "此appimportace ="
                    + info.importance
                    + ",context.getClass().getName()="
                    + context.getClass().getName());
            if (info.processName.equals(processName)) {
                Log.i(context.getPackageName(), "此appimportace ="
                        + info.importance
                        + ",context.getClass().getName()="
                        + context.getClass().getName());
                if (info.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台"
                            + info.processName);
                    return false;
                } else {
                    Log.i(context.getPackageName(), "处于前台"
                            + info.processName);
                    return true;
                }
            }
        }
        return false;
    }

}
